package com.imooc.common._this;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.imooc.chart.util.ImageMerger;
import com.imooc.common.controller.UserRequest;
import com.imooc.common.functional.FunctionHalper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.util.NutMap;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.BiFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * put /Users/dengwubo/tmp/gtp/2048/a.check /TripSettleInfoSend/upload
 * put /Users/dengwubo/tmp/gtp/2048/a.txt /TripSettleInfoSend/upload
 * put /Users/dengwubo/tmp/gtp/2048/a.sign /TripSettleInfoSend/upload
 * <p>
 * openssl dgst -sha256 -verify API_GATEWAY.pem  -signature test.sign  test.txt
 */
@Slf4j

public class MyTest {
    // private static final String FILE_NAME = "10000000000000149509_TripSettleInfoSend";
    private static final String FILE_NAME = "CJ2019111402353800001030_AIR_04_BACK";
    //  private static final String FILE_PATH = "/Users/dengwubo/tmp/gtp/ctrip/ctrip_test";
    private static final String FILE_PATH = "/Users/dengwubo/tmp/dengwb";
    private static final String SFTP_SHELL = "sftp -oIdentityFile=~/.ssh/id_rsa -oPort=8001 dengwb@106.120.68.100";
    //private static final String SFTP_SHELL = "sftp -oIdentityFile=/Users/dengwubo/tmp/gtp/ctrip/ctrip_test/id_rsa -oPort=8001 ctrip@106.120.68.100";
    private static final String SFTP_PATH = "/TripSettleInfoSend/upload";
    private static final String PRIVATE_PEM;
    private static final String PUBLIC_PEM;
    private static final String SRC_FILE;
    private static final String SIGN_FILE;
    private static final String CHECK_FILE;

    static {
        String privatePem = "{}/private.pem";
        PRIVATE_PEM = StrUtil.format(privatePem, FILE_PATH);
        String publicPem = "{}/public.pem";
        PUBLIC_PEM = StrUtil.format(publicPem, FILE_PATH);
        String srcFile = "{}/{}.BIN";
        SRC_FILE = StrUtil.format(srcFile, FILE_PATH, FILE_NAME);
        String signFile = "{}/{}.sign";
        SIGN_FILE = StrUtil.format(signFile, FILE_PATH, FILE_NAME);
        String checkFile = "{}/{}.check";
        CHECK_FILE = StrUtil.format(checkFile, FILE_PATH, FILE_NAME);
    }


    List<String> fileNames = new ArrayList<>();





    @Test
    public void testUrl(){
        String url= "https://dengwubo.mynatapp.cc/sso/oss/download/20231011/20231011144218427472.png";
    }

    @Test
    public void run33()throws Exception{
        List<String> strings = Arrays.asList("/Users/dengwubo/Pictures/tmp/1.jpg", "/Users/dengwubo/Pictures/tmp/2.png");
        ImageMerger.mergeImages(strings,"/Users/dengwubo/Pictures/tmp/merge.png","png");
    }


    @Test
    public void run32() throws Exception{
        int ceil = (int) Math.ceil(8 * 1.0 / 5);
        System.out.println(ceil);

    }
    @Test
    public void run31() throws Exception{

        String body = "{\"dataTableModel\":{\"draw\":2,\"columns\":[{\"data\":\"address\",\"name\":\"\",\"searchable\":true,\"orderable\":false,\"search\":{\"value\":\"\",\"regex\":false}},{\"data\":\"nameTag\",\"name\":\"\",\"searchable\":true,\"orderable\":false,\"search\":{\"value\":\"\",\"regex\":false}},{\"data\":\"balance\",\"name\":\"\",\"searchable\":true,\"orderable\":true,\"search\":{\"value\":\"\",\"regex\":false}},{\"data\":\"txnCount\",\"name\":\"\",\"searchable\":true,\"orderable\":true,\"search\":{\"value\":\"\",\"regex\":false}}],\"order\":[{\"column\":1,\"dir\":\"asc\"}],\"start\":0,\"length\":100,\"search\":{\"value\":\"\",\"regex\":false}},\"labelModel\":{\"label\":\"balancer\",\"subCategoryId\":\"1\"}}";
//        String post = HttpUtil.post("", body);
        HttpRequest post = HttpUtil.createPost("https://etherscan.io/accounts.aspx/GetTableEntriesBySubLabel");
        post.header("referer","https://etherscan.io/accounts/label/0x-protocol");
        post.header("origin","https://etherscan.io");
        post.header("cookie","ASP.NET_SessionId=q4p3f2w1r4vytbu5h0wyzue2; _ga=GA1.2.432370350.1675058441; __stripe_mid=086c88c6-ee6d-4227-93eb-c29d7ff08b24f5db04; etherscan_cookieconsent=True; etherscan_userid=dengwubo; etherscan_autologin=True; etherscan_pwd=4792:Qdxb:Bc8cgU0U5G+PuidIsj4BAIkMBEnNvaI7iC9Zuvvawxs=; __cflb=02DiuFnsSsHWYH8WqVXbZzkeTrZ6gtmGU9X5qC67U8zyA; _gid=GA1.2.432670654.1675304340; __cuid=ad2fe87802ab468494c1e9282f5700b2; amp_fef1e8=040d0bb2-8aad-42d9-9384-18addcb8b289R...1go7usql3.1go7v3dso.r.3.u; googtrans=/en/zh-CN; googtrans=/en/zh-CN; __cf_bm=WrD8KvJXsvKsuohrTL6R9oSPlUtHUd76c5LaeiWp0HQ-1675317502-0-AYdr540vU8THYuLoZdDPM24qMwC8LDcuBv2ASFgDgG4HeYl33ziEEX8vHTt0N4EqMnwsCQjrswDXhO+xrLJ7RJZueI5vYERNAE5HUMbU3SH1t5iKMaXd7t5VvVSukx7nv5A719HeGP68CkFt0ekP03Q=");
        post.header("x-requested-with","XMLHttpRequest");
        post.header("user-agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36");
        post.body(body);
        System.out.println(post);
        HttpResponse execute = post.execute(true);
        System.out.println(execute);
    }


    /**
     * : zh-CN,zh;q=0.9
     * :
     * :
     * Content-Length: 136
     * Content-Type: application/json;charset=UTF-8
     * Cookie: apm_ua=8DBBEC752B538D6F37BA4A2878298182; apm_uid=12E74F19CCFD9BF7B51D7FB561DBCEC6; apm_ct=20220909091706000; apm_ip=219.146.4.81; apm_sid=E3EA1DA1E2EBA617EA03B0C9A616EFB8
     * Host: sangazhen.sdszxc.com
     * Origin: https://sangazhen.sdszxc.com
     * sec-ch-ua: "Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"
     * sec-ch-ua-mobile: ?0
     * sec-ch-ua-platform: "macOS"
     * Sec-Fetch-Dest: empty
     * Sec-Fetch-Mode: cors
     * Sec-Fetch-Site: same-origin
     * User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36
     * @throws Exception
     */
    @Test
    public void run30() throws Exception{
        String auth = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkZW5nd3VibyIsImF1dGgiOiJjc2NwLmFuYWx5c2UuYXVkaXQsQzREVlY0Sk8sNEUwNUExQjcsMDJEQkFDNzksY216ei52aWxsYWdlck1hbmFnZW1lbnQuYXVkaXQsNTg1OUM2RDUsY3NjcC5sb2cubWFuYWdlbWVudCxERjQyQjY3MSw0RUQ3NUgzMSw2NzE2MUFCOCxjc2NwLndvcmtiZW5jaCxST0xFOkNBTUVSQTpTRUxFQ1RUUkVFQU5EQ0hJTERDQU1FUkFBUkVBLEY3MTMzNzAwLGNtenouZ29vZHNNYW5hZ2VtZW50LmF1ZGl0LDA0QkQxQThCLGNtenouY29tbXVuaXR5SW5mb3JtYXRpb24uYXVkaXQsODA4NDhBOEEsY3NjcC5zZW5kSW1tZWRpYXRlbHlQb2xpY3kuYXV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GFydHlhY3RpdmlzdHMsY216ei5hcHByb3ZlU25hcHNob3QuYXVkaXQsY3NjcC51c2VyLnF1ZXJ5LGNzY3AudXNlci5hZGQsY216ei5hcHByb3ZlU25hcHNob3QuYXVkaXQsY3NjcC5wbGF5LmF1ZGl0LGNzY3AuYXV0aG9yaXR5LGNzY3AudXNlci5kZWwsY3NjcC5sb2dnaW5nLm9wZXJhdGlvbixhdHRyLnJlc291cmNlQXR0ci5yZXNvdXJjZUF0dHJJbmZvLGNzY3AudXNlci5lZGl0LGF0dHIudGFnQXR0ci50YWdBdHRySW5mbyxjc2NwLnJvbGUsY3NjcC5wbGF0Zm9ybUhpc3RvcnkucXVlcnksY3NjcC5yb2xlLmFkZCxjc2NwLnJvbGUuZGVsLGNzY3Aucm9sZS5lZGl0LGNzY3Aub3JnLnF1ZXJ5LGNzY3Aub3JnLmVkaXQsY3NjcC5sb2dnaW5nLmxvZ2luLGNzY3AubG9nZ2luZy5vcGVyYXRpb24iLCJyZW0iOjAsImlkIjo3NCwidGVuYW50SWQiOiJzYW5nYXpoZW4iLCJpcCI6IjExMi4zOC42MS4xNiIsImlzc3VlZEF0IjoiMjAyMi0xMS0xOCAyMTo1NzozNSIsImV4cCI6MTY2ODg2NjI1NX0.aqf2VewBUj9Y8HoszWfjFbU0FbtryFEUDqzM3u6PdsbkDQ7CFQDiGqhiXF6UlvzdTLIk5W62a1aTcDcTTycfXw";
        Map<String,List<String>> headers = new HashMap<>();
        headers.put("Accept",Arrays.asList("application/json","text/plain", "*/*"));
        headers.put("Accept-Encoding",Arrays.asList("gzip","deflate","br"));
        headers.put("Accept-Language",Arrays.asList("zh-CN","zh;q=0.9"));
        headers.put("Authorization",Arrays.asList(auth));
        headers.put("Connection",Arrays.asList("keep-alive"));
        Map<String,Object> busiParam = new HashMap<>();
        busiParam.put("busiParam",null);
        busiParam.put("pageNumber",1);
        busiParam.put("processType","cmrz");
        busiParam.put("pageSize",50);

        HttpResponse execute = HttpUtil.createPost("https://sangazhen.sdszxc.com/console/office/api/acti/getTodoTaskList")
                .header(headers).body("{\"pageNumber\":1,\"pageSize\":10,\"busiParam\":{\"ext\":4,\"keyword\":\"\",\"title\":\"\",\"applicantUserName\":\"\",\"sealName\":\"\"},\"processType\":\"cmrz\"}")
                .execute();
        ;
        System.out.println(execute);
        NutMap map = JSONUtil.toBean(execute.body(), NutMap.class);
        NutMap data = map.getAs("data", NutMap.class);
//        NutMap data = (NutMap) map.get("data", NutMap.class);
        System.out.println(data);
        List<NutMap> list = data.getList("list", NutMap.class);
        System.out.println(list);

        List<NutMap> nameList = list.stream().filter(item -> StrUtil.isNotBlank(item.getString("name"))).collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(nameList));
        nameList.forEach(item->{
            Map<String,Object> params = new HashMap<>();
            params.put("taskId",item.getString("taskId"));
            params.put("procInstId",item.getString("procInstId"));
            params.put("comment","同意");
            params.put("bid",item.getString("bid"));
            params.put("busiId",item.getInt("id"));
            params.put("operationType",1);
            params.put("processType","cmrz");
            HttpResponse httpResponse = HttpUtil.createPost("https://sangazhen.sdszxc.com/console/office/api/acti/operationType")
                    .header(headers).body(JSONUtil.toJsonStr(params))
                    .execute();
            System.out.println(JSONUtil.toJsonStr(params));

        });



        /**
         * {"taskId":"1814224","procInstId":"1814200","comment":"1","bid":"cmrz2028","busiId":2028,"operationType":1,"processType":"cmrz"}
         */



    }

    @Test
    public void delByName() throws Exception{
/*        String fileName = "E:\\code\\gmk-kpi-vue\\node_modules";

        Runtime runtime = Runtime.getRuntime();
        String[] args = new String[] {"cmd.exe", "/c", String.format("rd /q /s %s", fileName)};
        runtime.exec(args);*/

        traverseFolder("E:\\code");
//        System.out.println(JSONUtil.toJsonStr(fileNames));


    }



    private void traverseFolder(String path) {

        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory() && !StrUtil.equalsAny( file2.getName(),"target","node_modules")) {
                        traverseFolder(file2.getAbsolutePath());
                    } else if (file2.isDirectory() && StrUtil.equalsAny( file2.getName(),"node_modules")) {
                        System.out.println("find: "+file2.getAbsolutePath());
                        Files.deleteDir(new File(file2.getAbsolutePath()));

//                        fileNames.add(file2.getAbsolutePath());
                    } else {
//                        System.out.println("文件:" + file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }


    @Test
    public void fileProgress() throws Exception {
        sourceFileGen();
        signFileGen();
        signFileVerify();
        checkFileGen();


    }


    @Test
    public void mapGen() throws Exception {

        BiFunction<String, Object, Map> mapBiFunction = FunctionHalper.generaterMap();

        Map apply = mapBiFunction.apply("key", "value");
        log.error("apply is {}", JSONUtil.toJsonStr(apply));

    }


    @Test
    public void sourceFileGen() throws Exception {
        String text = "{} is a test file 中文测试 !!!";
        text = StrUtil.format(text, FILE_NAME);
        boolean exist = FileUtil.exist(SRC_FILE);
        if (!exist) {
            File file = Files.createFileIfNoExists(SRC_FILE);
            Files.write(file, text);
        }

    }

    @SuppressWarnings("all")
    public void checkFileGen() throws Exception {
        NutMap checkMap = NutMap.NEW();
        NutMap fileInfo = NutMap.NEW();
        String sourceFileSize = String.valueOf(FileUtil.size(new File(SRC_FILE)));
        String signFileSize = String.valueOf(FileUtil.size(new File(SIGN_FILE)));
        String sourceFile = Files.getName(SRC_FILE);
        String signFile = Files.getName(SIGN_FILE);
        fileInfo.put("sourceFile", sourceFile);
        fileInfo.put("sourceFileSize", sourceFileSize);
        fileInfo.put("signFile", signFile);
        fileInfo.put("signFileSize", signFileSize);
        fileInfo.put("remark", "test");

        checkMap.put("fileInfo", fileInfo);

        String s = JSONUtil.toJsonStr(checkMap);
        System.out.println(s);

        File checkFile = Files.createFileIfNoExists(CHECK_FILE);
        Files.write(checkFile, s);

        String putTemp = "put {} {}";
        String checkPutStr = StrUtil.format(putTemp, CHECK_FILE, SFTP_PATH);
        String filePutStr = StrUtil.format(putTemp, SRC_FILE, SFTP_PATH);
        String signPutStr = StrUtil.format(putTemp, SIGN_FILE, SFTP_PATH);
        System.out.println(SFTP_SHELL);
        System.out.println(checkPutStr);
        System.out.println(filePutStr);
        System.out.println(signPutStr);
    }


    @Test
    public void signFileGen() throws Exception {
        Process process = null;
        String template = "openssl dgst -sha256 -sign {} -out {} {}";
        String sginShellStr = StrUtil.format(template, PRIVATE_PEM, SIGN_FILE, SRC_FILE);
        process = callShell(sginShellStr);
        printLogs(process);
    }

    @Test
    public void signFileVerify() throws Exception {
        Process process = null;
        String template = "openssl dgst -sha256 -verify {} -signature {}  {}";
        String sginShellStr = StrUtil.format(template, PUBLIC_PEM, SIGN_FILE, SRC_FILE);
        process = callShell(sginShellStr);
        printLogs(process);
    }

    public static void printLogs(Process process) throws Exception {
        List<String> processList = new ArrayList<String>();
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        while ((line = input.readLine()) != null) {
            processList.add(line);
        }
        for (String msg : processList) {
            log.debug(msg);
        }
    }

    public static Process callShell(String shellString) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(shellString);
            int exitValue = process.waitFor();
            if (0 != exitValue) {
                log.error("call shell failed. error code is : {}", exitValue);
            }
        } catch (Throwable e) {
            log.error("call shell failed. {}", e);
        }

        return process;
    }


    @Test
    public void run16() {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> user = new HashMap<>();
        user.put("name", "zhangsan");
        user.put("age", 11);
        map.put("id", "456");
        map.put("user", user);
        String mapStr = JSONUtil.toJsonStr(map);
        System.out.println(mapStr);
        Map toBean = JSONUtil.toBean(mapStr, Map.class);
        System.out.println(toBean);
        Object object = toBean.get("user");
        Map userMap = (Map) object;
        System.out.println(userMap);


    }

    @Test
    public void run15() {
        UserRequest userRequest = new UserRequest();
        userRequest.setTest("test");
        User user = new User();
        user.setId(123l);
        user.setName("zhangsan");
        Role role = new Role("456", "lisi");
        user.setRoles(Arrays.asList(role));

        userRequest.setUser(user);
        String s = JSONUtil.toJsonStr(userRequest);
        System.out.println(s);

    }


    @Test
    public void run14() throws Exception {
        byte[] data = "HELLO".getBytes();
        Sign sign = SecureUtil.sign(SignAlgorithm.SHA1withRSA);

        byte[] signed = sign.sign(data);
        String s = new String(signed);
        System.out.println(s);

        boolean verify = sign.verify(data, signed);
        System.out.println(verify);

        FileOutputStream fileOutputStream = new FileOutputStream("NioTest3.txt");
        FileChannel fileChannel = fileOutputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(512);


        for (int i = 0; i < signed.length; i++) {

            buffer.put(signed[i]);
        }
        buffer.flip();
        fileChannel.write(buffer);
        fileOutputStream.close();
    }


    @Test
    public void run13() {
        String str = "{\"url\":\"https:\\/\\/apipcs4.dccnet.com.cn\\/api\\/mall\\/trip\\/planeissue\\/V1\",\"content\":\"app_id=10000000000000051504&biz_content={\\\"appId\\\":\\\"10000000000000051504\\\",\\\"data\\\":{\\\"passengerTickets\\\":[{\\\"ticketPNR\\\":\\\"\\\",\\\"ticketNO\\\":\\\"7855510004331\\\",\\\"passengerName\\\":\\\"\\u5eb7\\u9759\\u857e\\\",\\\"bigCode\\\":\\\"\\\"}],\\\"orderNo\\\":\\\"020190725102643000000000005184\\\"},\\\"returnCode\\\":\\\"000000\\\",\\\"returnMsg\\\":\\\"\\u51fa\\u7968\\u6210\\u529f\\\"}&charset=UTF-8&format=json&msg_id=b03088ed08de662f30524567c064bb6f&sign=OAVo8asyU98CLlxifBDfz3hjedwjtNCuR6eJ%2FtcgvZ3f4FaUMP4Kcn6O4ypIniWs7p8oeOrNZXs%2FE4%2B%2Btk9wzWQWgqszolhigfgfJaaBj7COEepoohUhNjB4FbpXFVj9ggKM40Y6DUCM%2ByQxzE%2F5a%2FtZR7rIstcyRmz6G5AHZnXOAk2%2FECwqHcBX86vS4yRBlWxCxiGq1OYWZu8skqTNET52vDrS4LTq6ZRCh2Y3%2FeihuW%2FGWjTYquFePjNmOH5DY7oVmxjGJkW4TH%2B1ZgYfehW95ZbO0kou6jebkWx%2BV7MhPpKzZZk%2Bl%2BOiLOW4DSTV0bMw1CgR3A%2FnFEAp3TeHgA%3D%3D&sign_type=RSA&timestamp=2019-07-23  10:33:46\"}";

        str = str.replace("\\", "");
        System.out.println(str);

    }

    @Test
    public void run12() {
        String s = "%e9%82%93%e6%ad%a6%e5%8d%9a";
        String decode = URLUtil.decode(s);
        System.out.println(decode);

    }

    @Test
    public void run11() {
        String a = "2017-05-06 02:57";
        Date value = Convert.toDate(a);
        System.out.println(value);

        double b = 67556000000000.32;

//结果为："陆万柒仟伍佰伍拾陆元叁角贰分"
        String digitUppercase = Convert.digitToChinese(b);
        System.out.println(digitUppercase);
    }


    /**
     * 火车票退票费率计算
     */
    @Test
    public void run10() {
        BigDecimal v = CancelFee(new BigDecimal(12));
        System.out.println(v);


    }

    public BigDecimal CancelFee(BigDecimal price) {

        BigDecimal percent = new BigDecimal(0.2);

        BigDecimal num = price.multiply(percent);
        BigDecimal bigDecimal = num.setScale(1, RoundingMode.UP);


        return bigDecimal;

    }


    @Test
    public void run9() {
        String s = ",,0101";
        String regex = "(.*)(,)(.*)";
        Pattern pat = Pattern.compile(regex);
        Matcher mat = pat.matcher(s);
        mat.find();
        System.out.println(mat.group(3));


    }


    /**
     * 损失率计算
     */
    @Test
    public void refundTest() {
        BigDecimal subPrice = new BigDecimal(6);
        BigDecimal parentPrice = new BigDecimal(4);
        BigDecimal totalPrice = new BigDecimal(10);
        BigDecimal refundPrice = new BigDecimal(8);
        BigDecimal subPercent = subPrice.divide(totalPrice, 2, RoundingMode.DOWN);

        subPrice = refundPrice.multiply(subPercent);
        parentPrice = refundPrice.subtract(subPrice);

        System.out.println("subPrice is " + subPrice);
        System.out.println("parentPrice is " + parentPrice);


    }


    @Test
    public void run1() {
        User user = new User();
        user.setId(1l);
        user.setName("zhangsan");
        Map<String, Object> save = user.save();
        System.out.println(save);

    }

    @Test
    public void run2() {
        BigDecimal num1 = new BigDecimal(-1);
        int i = num1.compareTo(BigDecimal.ZERO);
        System.out.println(i);

    }

    @Test
    public void run3() {
        User user = new User();
        List<Role> roles = new ArrayList<>();
        roles.add(new Role("1", "zhangsan"));
        roles.add(new Role("2", "lisi"));
        user.setRoles(roles);
        packageUser(user);


        System.out.println(Json.toJson(user));


    }

    @Test
    public void run4() {
        Map<String, Object> map = new HashMap<>();
        List<String> list = Arrays.asList("1111", "22222", "33333");
        String appId = "appId";
        map.put("loginIds", list);
        map.put("appId", appId);
        batch(map);
//
    }

    @Test
    public void run5() {
        String ids = "111,222,";
        List<String> strings = Arrays.asList(ids.split(","));
        System.out.println(strings);
        System.out.println(strings.size());


    }

    @Test
    public void run6() {
        String s = "20190101";
        String regex = "(.{4})(.{2})(.{2})";
        String res = s.replaceAll(regex, "$1-$2-$3");
        System.out.println(res);

    }

    @Test
    public void run7() {
      /*  BigDecimal totalPrice = new BigDecimal(123.4);
        BigDecimal price = new BigDecimal(12.34);
        BigDecimal divide = price.divide(totalPrice, 2, RoundingMode.DOWN);

        BigDecimal parentPrice = new BigDecimal(100.4);
        BigDecimal childPrice = totalPrice.subtract(parentPrice).setScale(2);*/

        char[] chars = new char[3];
        String s = new String(chars);
        System.out.println(s);
        String target = s.replace('\0', '0');
        System.out.println(target);


    }


    @Test
    public void run8() {
        List<Integer> integers = Arrays.asList(1);
        integers = integers.stream().distinct().collect(Collectors.toList());
        System.out.println(integers);
    }


    public void packageUser(User user) {
        user.getRoles().forEach(role -> {
            role.setName("test");
        });

    }


    public void batch(Map<String, Object> map) {

        List<String> loginIds = map.get("loginIds") instanceof List<?> ? (List<String>) map.get("loginIds") : new ArrayList<>();
        String appId = map.get("appId") instanceof String ? (String) map.get("appId") : null;

        System.out.println(loginIds);
        System.out.println(appId);

    }


    @Test
    public void run17() throws Exception {
        Object num = 15;

        String s = String.valueOf(num);
        System.out.println(s);


        Map map = new HashMap();
        map.put("num", 0);

        String num1 = String.valueOf(map.get("num"));
        System.out.println(num1);

    }

    private String XYZ = "";

    @Test
    public void run18() throws Exception {
        XYZ = "xxxxx";
        run18_();
    }

    void run18_() {
        System.out.println(XYZ);
    }

    @Test
    public void run19() throws Exception {
        Date date = new Date();
        System.out.println(date);
        String mMdd = DateUtil.format(date, "MMdd");
        System.out.println(mMdd);
        //如果当前时间小于8:00则取昨天的时间
        Date clockEight;
        Calendar calendar = Calendar.getInstance();
        calendar.set(DateUtil.year(date),
                DateUtil.month(date),
                DateUtil.dayOfMonth(date),
                8, 0, 0);
        clockEight = calendar.getTime();

        DateTime eightTime = DateTime.of(clockEight);
        DateTime nowTime = DateTime.of(new Date());
        System.out.println(nowTime);
        System.out.println(eightTime);
        System.out.println(nowTime.isBefore(eightTime));

        String dayByClock = getDayByClock();
        System.out.println(dayByClock);

    }


    @Test
    public void run20() throws Exception {
        double longitude = 121.4;
        String df = new DecimalFormat("0000.0").format(121d);
        System.out.println(df);
        System.out.println(new BigDecimal(df).toString());


    }

    @Test
    public void run21() throws Exception {
        List<Map> currentMap = new ArrayList<>();
        Map<String, Object> landN = new HashMap<>();
        landN.put("length", 1.1);
        landN.put("number", 20);
        currentMap.add(landN);
        landN = new HashMap<>();
        landN.put("length", 1.1);
        landN.put("number", 10);
        currentMap.add(landN);
        landN = new HashMap<>();
        landN.put("length", 2.1);
        landN.put("number", 20);
        currentMap.add(landN);
        landN = new HashMap<>();
        landN.put("length", 2.1);
        landN.put("number", 20);
        currentMap.add(landN);
        landN = new HashMap<>();
        landN.put("length", 3.1);
        landN.put("number", 20);
        currentMap.add(landN);
        landN = new HashMap<>();
        landN.put("length", 3.1);
        landN.put("number", 200);
        currentMap.add(landN);

        Map<Object, List<Map>> length = currentMap.stream().collect(Collectors.groupingBy(d -> d.get("length")));
        System.out.println(JSONUtil.toJsonStr(length));
        Collection<List<Map>> values = length.values();
        System.out.println(JSONUtil.toJsonStr(values));

        List<Map<String, Object>> maps = new ArrayList<>();
        for (List<Map> value : values) {
            int number = 0;
            double _length = 0;
            for (Map map : value) {
                number += (int) map.get("number");
                _length = (double) map.get("length");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("length", _length);
            map.put("number", number);
            maps.add(map);
        }
        System.out.println(JSONUtil.toJsonStr(maps));

    }


    @Test
    public void run22() throws Exception {
        String s = "T20L1231";
        System.out.println(s.matches("^[a-zA-Z].*"));

        int monthValue = DateUtil.offsetMonth(new Date(), 0).month();


        System.out.println(monthValue);

        monthValue = LocalDate.now().getMonthValue();
        System.out.println(monthValue);
        monthValue = LocalDate.now().minusMonths(1).getMonthValue();
        System.out.println(monthValue);
        LocalDate localDate = LocalDate.now().minusMonths(1);
        System.out.println(localDate.toString());


    }

    private String getDayByClock() {
        Date date = new Date();
        Date clockEight;
        Calendar calendar = Calendar.getInstance();
        calendar.set(DateUtil.year(date),
                DateUtil.month(date),
                DateUtil.dayOfMonth(date),
                8, 0, 0);
        clockEight = calendar.getTime();

        DateTime eightTime = DateTime.of(clockEight);
        DateTime nowTime = DateTime.of(new Date());

        if (nowTime.isBefore(eightTime)) {
            // 8:00 之前用昨天的日期
            return DateUtil.format(DateUtil.offsetDay(nowTime, -1), "dd");
        } else {
            return DateUtil.format(nowTime, "dd");
        }

    }

    @Test
    public void run23() {
        System.out.println(DateUtil.now());
        String regx = "(.{4})-(.{2})-(.{2})(.*)";
        String day = DateUtil.now().replaceAll("(.{4})-(.{2})-(.{2})(.*)", "$3");
        System.out.println(day);

    }

    @Test
    public void run24() {

        String s = StrUtil.isNotBlank("494.50") ? new BigDecimal("494.50").setScale(1) + "" : "0";
        System.out.println(s);

        LocalDateTime parse = LocalDateTime.parse("2021-01-16T12:00:00");
        System.out.println(parse);

    }

    @Test
    public void run25() {
        System.out.println(DateUtil.now());
        String regx = "(.{4})-(.{2})-(.{2}) (.{2}):(.{2}):(.{2})";
        String clock = DateUtil.now().replaceAll(regx, "$4$5$6");
        System.out.println(clock);

    }

    @Test
    public void run26() {
        DateTime lastMonth = DateUtil.offset(new Date(), DateField.MONTH, -1);

        int year = lastMonth.year();
        int month = lastMonth.month();
        lastMonth = DateUtil.beginOfMonth(lastMonth);

        for (int i = month; i >= 0; i--) {
            DateTime offset = DateUtil.offset(lastMonth, DateField.MONTH, -i);
            System.out.println(offset);
        }
    }

    @Test
    public void run27() {
        DateTime dateTime = DateUtil.parseDate("2020-12-31");
        System.out.println(dateTime);

    }
    private static void saveObjMulThread(int s, String saveEntityStr) throws Exception {
        List<Object> saveEntityList = new ArrayList<Object>();
        for (int i = 0; i < s; i++) {
            Object saveEntity = Class.forName(saveEntityStr).newInstance();
            //省略赋值操作
            saveEntityList.add(saveEntity);
        }
        //每500条数据开启一个线程
        int threadSize =500;
        List<List<Object>> pList = ListUtils.partition(saveEntityList, threadSize);
        //总数据条数
//        int dataSize = saveEntityList.size();
        //线程数
        int threadNum=pList.size();
        //创建线程池,--拥有固定线程数量的线程池（推荐）
        ExecutorService exc = Executors.newFixedThreadPool(threadNum);
        //定义可以提交给线程池的任务集合
        List<Callable<List<String>>> tasks = new ArrayList<>();
        //每个线程的任务
        Callable<List<String>> task = null;
        //定义切割总List集合后的集合
        List<Object> cutList = null;

        //遍历任务
        for (List<Object> paramList : pList) {
            task = new Callable<List<String>>() {
                @Override
                public List<String> call() throws Exception {
                    //定义接收业务返回值的集合
                    List<String> newList = new ArrayList<>();
                    //Session s = SessionUtil.getSession("sessionFactory");
//                    SessionFactory sf = (SessionFactory) SpringContextHolder.getBean("sessionFactory");
//                    Session s = sf.openSession();
//                    s.getTransaction();
//                    if (!s.getTransaction().isActive()) {
//                        //开启事务
//                        s.beginTransaction();
//                    }
//                    //处理自己的业务，这里挑选基数
//                    for (Object a : paramList) {
//                        s.save(a);
//                    }
//                    s.getTransaction().commit();
//                    s.close();
                    return newList;
                }
            };
            //添加任务
            tasks.add(task);
        }

        List<String> fanList =new ArrayList<>();
        try {
            //执行所有任务并获取结果,捕获异常InterruptedException
            List<Future<List<String>>>  results = exc.invokeAll(tasks);
            for (Future<List<String>> result : results){
                //调用get方法获取每个返回的结果，将结果添加到定义好的集合中。捕获异常ExecutionException
                fanList.addAll( result.get());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //关闭线程池
        exc.shutdown();
    }
}
